package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0") //声明这是一个dobbu服务,程序启动之后会将该服务注册到zk的注册中心去
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryWithMaxScore(Long userId) { //方法的参数指的是登录的用户
        //查询得分最高的用户
        //注:recommend_user表中的userId是系统给推荐的用户,而toUserId才是登录的用户;
        Query query = Query.query(Criteria.where("toUserId").is(userId)) //筛选当前用户在recommend_user表中的推荐信息
                .with(Sort.by(Sort.Order.desc("score"))).limit(1); //按照score降序排序,筛选第一个
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {

        //构造分页:传递分页&排序信息
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Order.desc("score")));
        //pageNum要-1,因为mongodb查询页是从0开始的
        Query query = Query.query(Criteria.where("toUserId").is(userId))
                .with(pageRequest);

        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);

        //参数1:数据总条数Integer total因前端暂时不需要该数据,因此不做返回
        return new PageInfo<>(0,pageNum,pageSize,recommendUserList);
    }

    @Override
    public double queryScore(Long userId, Long toUserId) {
        Query query = Query.query(Criteria
                .where("toUserId").is(toUserId)
                .and("userId").is(userId));
        RecommendUser recommendUser = this.mongoTemplate.findOne(query, RecommendUser.class);
        if (null == recommendUser) {
            return 0;
        }
        return recommendUser.getScore();
    }
}
